package com.jpro.module.infra.api.config;

import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.module.infra.api.config.dto.ConfigUpdateReqVO;
import com.jpro.module.infra.dal.dataobject.config.ConfigDO;
import com.jpro.module.infra.enums.ErrorCodeConstants;
import com.jpro.module.infra.service.config.ConfigService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jpro.framework.common.pojo.CommonResult.success;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class ConfigApiImpl implements ConfigApi {

    @Resource
    private ConfigService configService;

    @Override
    public CommonResult<String> getConfigValueByKey(String key) {
        ConfigDO config = configService.getConfigByKey(key);
        return success(config != null ? config.getValue() : null);
    }

    public CommonResult<String> getConfigKey(String key) {
        ConfigDO config = configService.getConfigByKey(key);
        if (config == null) {
            return null;
        }
        if (!config.getVisible()) {
            throw exception(ErrorCodeConstants.CONFIG_GET_VALUE_ERROR_IF_VISIBLE);
        }
        return success(config.getValue());
    }

    @Override
    public CommonResult<Boolean> updateConfigForApi(ConfigUpdateReqVO reqVO) {
        configService.updateConfigForApi(reqVO);
        return success(true);
    }
}
